package com.dai.rpc.loadbanlance.loadbanlancer;

import com.dai.rpc.factory.SingletonFactory;
import com.dai.rpc.loadbanlance.AbstractLoadBalance;
import com.dai.rpc.message.RpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * 轮询策略
 */
@Slf4j
public class HashBalance extends AbstractLoadBalance {


    @Override
    protected String doSelect(List<String> serviceUrlList, RpcRequest rpcRequest) {
        Random random = SingletonFactory.getInstance(Random.class);
        return serviceUrlList.get(random.nextInt(serviceUrlList.size()));
    }


    @Override
    protected InetSocketAddress doLoadBalance(Set<String> services) {

        if(services.size() <= 0) return null;
        log.info("使用源地址负载均衡策略...");
        ArrayList<String> list = new ArrayList<>(services);
        // 获取客户端的Ip地址,用该hash值对服务器列表的大小进行取模运算
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            int hashCode = ip.hashCode();
            int size = list.size();
            int index = hashCode % size;
            String[] s = list.get(index).split(",");

            return new InetSocketAddress(s[0],Integer.parseInt(s[1]));

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public String name() {
        return "hash";
    }
}
